home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4460 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  45 lines

  1. Newsgroups: comp.lang.c
  2. Path: Utrecht.NL.net!news
  3. From: Franz Korntner <fkorntne@bazis.nl>
  4. Subject: Re: random number
  5. X-Nntp-Posting-Host: bastion1.bazis.nl
  6. Content-Type: text/plain; charset=us-ascii
  7. Message-ID: <3115D5B3.41C6@bazis.nl>
  8. Sender: news@inter.NL.net (News at newsutr)
  9. Content-Transfer-Encoding: 7bit
  10. Organization: NLnet
  11. Mime-Version: 1.0
  12. Date: Mon, 5 Feb 1996 10:02:27 GMT
  13. X-Mailer: Mozilla 2.0b6a (X11; I; OSF1 V3.2 alpha)
  14.  
  15. > >Hi,
  16. > >Could anybody help me to generate some code to produce
  17. > >a random number between -3 and 3 ?
  18. > >I'm trying to use rand(), but since it doesn't receive
  19. > Each time you call rand map the result into the interval -3 ... 3.
  20. > You can do this, for example, as follows:
  21. >    r = (rand() % 7) - 3;
  22. > If you are using rand be sure and read about the role of srand
  23. > in "initializing" the sequence of random numbers that are generated.
  24.  
  25. You are using rand()%7 to get a number in the range 0..7 but this method is
  26. incorrect. Performing operations on random numbers is okay as long as all
  27. bits of the number are included in the operation. It is known to be
  28. dangerous to extract bits from a pseudo-random number and assume that those
  29. bits have random properties. Even worse, it is also known that the less
  30. significant bits of some random number generators are not random at all! In
  31. this case you are selecting the 3 most less significant bits of the number,
  32. the worst choice that could have been made. A better solution is to use the
  33. magnitude of the random number, but such operations are implemention
  34. dependent (overflows, and such) as in:
  35.   (rand()*7)/(MAXRAND+1)
  36.  
  37. -- 
  38. +-----------------------------------------------------------------------+
  39. | Franz Korntner at BAZIS, dept. System Development, Leiden, Netherlands|
  40. | E-mail: fkorntne@bazis.nl                                             |
  41. +-----------------------------------------------------------------------+
  42.